package com.markby.fscm.custom.interceptor;

import com.markby.fscm.common.login.LoginUserHolder;
import com.markby.fscm.constant.Constants;
import com.markby.fscm.domain.form.LoginUser;
import com.markby.fscm.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader(Constants.REQUEST_HEADER_ACCESS_TOKEN);
        Claims claims =JwtUtil.parseToken(token);

        String uuid = claims.get(Constants.CLAIM_UUID, String.class);
        String randomNum = claims.get(Constants.CLAIM_RANDOM_NUM, String.class);
        String source = claims.get(Constants.CLAIM_SOURCE, String.class);


        LoginUserHolder.setLoginUser(new LoginUser(uuid, randomNum,"", source));

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        LoginUserHolder.clear();
    }
}